import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//1.引入element-plus组件库
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
//3.引入element-plus图标库
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//5.1修改elementPlus默认中文
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from "axios";

//9.1 配置根路径
const BASE_URL = 'http://localhost:7070';
//window对象是浏览器内置的全局对象,给它设置的属性就是全局属性,可以在任意script标签中使用!
window.BASE_URL = BASE_URL;
const app = createApp(App)
//9.2 给app(vue实例)也设置根路径,这样可以在任意template标签中使用!
app.config.globalProperties.BASE_URL = BASE_URL;

//4.遍历ElementPlusIconsVue对象中的所有图标组件并注册到app中
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

//2.app.use(ElementPlus) 使用Element-plus组件库
//5.2 app.use(ElementPlus,{ locale: zhCn })将El本地化为中文
app.use(ElementPlus,{ locale: zhCn }).use(store).use(router).mount('#app')

//6.解决ResizeObserver Error
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}

//7.配置全局方法,获取当前登录人的数据
window.getUser = () => {
    return localStorage.user ? JSON.parse(localStorage.user) : null;
}

//8.设置路由守卫
//to即将要访问的目标 from即将离开的目标 next路由守卫执行的函数
router.beforeEach((to, from, next) => {
    let user = localStorage.user;//从localStorage中获取用户数据
    if(to.path!=='/login' && !user)//如果目标路径不是登录页且用户不存在
        //就跳转到登录页,且弹出提示
        next({path: '/login'},ElMessage.error('请先登录!'));
    else
        next()//如果目标路径是登录页,或用户已登录,就直接放行,允许路由跳转
})

//10.创建根据字典code查询此字典下所有字典项的全局方法
window.loadDictOptions = (object,dictCode) => {
    axios.get(BASE_URL+'/v1/dictoption/select/'+dictCode)
        .then((response)=>{
            if(response.data.code==2000){
                object.value = response.data.data;
            }else{
                ElMessage.error(response.data.message);
            }
        })
}


